var voiceidone=""; //上一个播放的audio标签的id
var serceridone = '';
var localId = '';
var serverId = '';

var groupId = "<?=$this->data['群id']?>";
//var images = {
//    localId: [],
//    serverId: []
//};

var u = navigator.userAgent, app = navigator.appVersion;
var isAndroid = u.indexOf('Android') > -1 || u.indexOf('Linux') > -1; //android终端或者uc浏览器
var isiOS = !!u.match(/\(i[^;]+;( U;)? CPU.+Mac OS X/); //ios终端
var isClickHistory = false;

wx.config({
    debug: false,
    appId: '<?php echo $this->signPackage["appId"];?>',
    timestamp: '<?php echo $this->signPackage["timestamp"];?>',
    nonceStr: '<?php echo $this->signPackage["nonceStr"];?>',
    signature: '<?php echo $this->signPackage["signature"];?>',
    jsApiList: [
        'startRecord',
        'stopRecord',
        'onRecordEnd',
        'playVoice',
        'pauseVoice',
        'stopVoice',
        'uploadVoice',
        'downloadVoice',
        'chooseImage',
        'previewImage',
        'uploadImage',
        'downloadImage',
        'onVoiceRecordEnd'
    ]
});

wx.ready(function(){
    wx.hideOptionMenu(); //隐藏右上角菜单接口
});


var appKey = "611d56bcd17bdfa4a83e5bdf55916589";
var account = "<?=$_SESSION['userCenter']['id']?>";
var token = "<?=$_SESSION['userCenter']['token']?>";
var chatId = "<?=$this->data['chatId']?>";
var chatroomObj;
var timeStamp = '';
var msgReturnNum; //单次实际返回消息数
var msgGetNum = 50; //单次获取历史消息数

console.log(account);
console.log(token);

var nim = NIM.getInstance({
    debug: true,
    appKey: appKey,
    account: account,
    token: token,
    onconnect: onConnect
});

var online_time_interval = setInterval('online_time()', 10000); //记录在线时长

//查看历史消息
$("#view_history_news").click(function() {
    isClickHistory = true;
    if(msgReturnNum == msgGetNum){
        if ($("#message_box").scrollTop() <= 0) {
            chatroomObj.getHistoryMsgs({
                timetag: timeStamp,  // 不填表示当前时间戳
                limit: msgGetNum, //100条
                done: getHistoryMsgsDone
            });
        }
    }
});

//发文本
$(".send-btn").click(function() {
    var text = $.trim($("#message").val());
    var msg = chatroomObj.sendText({
        text: text,
        done: sendChatroomMsgDone
    });
});

//发图片
$("#sendPic").change(function(){
    chatroomObj.previewFile({
        type: 'image',
        fileInput: sendPic,
        uploadprogress: function(obj) {
            console.log('文件总大小: ' + obj.total + 'bytes');
            console.log('已经上传的大小: ' + obj.loaded + 'bytes');
            console.log('上传进度: ' + obj.percentage);
            console.log('上传进度文本: ' + obj.percentageText);
        },
        done: function(error, file) {
            console.log('上传image' + (!error?'成功':'失败'));
            console.log('file:' + JSON.stringify(file));
            // show file to the user
            if (!error) {
                var msg = chatroomObj.sendFile({
                    file: file,
                    type : 'image',
                    done: sendChatroomMsgDone
                });
                console.log('正在发送聊天室image消息, id=' + msg.idClient);
            }
        }
    });
});

$("#wx_uploadPic").click(function(){
    if(isAndroid){
        $(".class_talk_con_header video").hide();
    }
    wx.chooseImage({
        count: 1, // 默认9
        sizeType: ['compressed'], // 可以指定是原图还是压缩图，默认二者都有
        sourceType: ['album', 'camera'], // 可以指定来源是相册还是相机，默认二者都有
        success: function (res) {
            $(".class_talk_con_header video").show();
            localIds = res.localIds; // 返回选定照片的本地ID列表，localId可以作为img标签的src属性显示图片

            var localId = localIds.pop();
            wx.uploadImage({
                localId: localId,
                isShowProgressTips: 1,
                success: function (res) {
                    var imageId = res.serverId; // 返回图片的服务器端ID

                    re = common.get('group', 'downLoadWxFile', {'serverId':imageId, 'type':'image'});
                    console.log('下载图片：'+JSON.stringify(re));
                    if (re.result == 0) {
                        file = re.datas;
                        var msg = chatroomObj.sendFile({
                            file: file,
                            type : 'image',
                            done: sendChatroomMsgDone
                        });
                        console.log('正在发送聊天室Image消息, id=' + msg.idClient);
                    }
                }
            });
        }
    });
});

//显示录音按钮
$("#display_audio").click(function() {
    $("#class_talk_con_footer_frame").addClass("audio_xx");
    $(".m_hide").show();
    $(".m_show").hide();
    $(".closeabs").show();
});

//开始录音
$("#start_record_audio").click(function() {
    $(".time-bg").show();
    $(".class_talk_con_footer_icon_audio_off").show();
    $(".class_talk_con_footer_icon_audio_on").hide();
    $(".floorbg").show();
    startluyin();
    setTimeout(show123(60),1000);
    auto_stop();
    $(".class_talk_con_footer_fffffficon_audio_on").attr("luyin",1);
});

//发送录音
$("#send_audio").click(function() {
    $(".time-bg").hide();
    $(".class_talk_con_footer_icon_audio_on").show();
    $(".class_talk_con_footer_icon_audio_off").hide();
    $(".floorbg").hide();
    clearTimeout(dingshi);
    stopluyin();
    $(".class_talk_con_footer_icon_audio_on").attr("luyin",0);
    footerfunction();
    $("#class_talk_con_footer_frame").removeClass("audio_xx");
    $(".m_show").show();
    $(".m_hide").hide();
    $(".closeabs").hide();
});


//表情列表
for(var i in emoji){
    console.log(emoji[i].file);
    var mess = "<span class='expression' val='"+i+"' style=''><img style='width: 24px;height: auto;padding-right: 5px;padding-bottom:5px;' src='business/images/emoji/"+emoji[i].file+"' /></span>"
    $("#emojiTag").append(mess);
}

$(".expression").click(function(){
    var expression = $(this).attr('val');
    $("#emojiTag").hide();
    $("#message").val($("#message").val()+expression);
});

$(".show_emoji").click(function(){
    $("#emojiTag").show();
});

function onConnect() {
    console.log('连接成功');
    nim.getChatroomAddress({
        chatroomId: chatId,
        done: getChatroomAddressDone
    });
    function getChatroomAddressDone(error, obj) {
        console.log('获取聊天室地址' + (!error?'成功':'失败'), error, obj);
        if(!error){
            chatroomObj = Chatroom.getInstance({
                appKey: appKey,
                account: account,
                token: token,
                chatroomId: chatId,
                chatroomAddresses: obj.address,
                onconnect: onChatroomConnect,
                onerror: onChatroomError,
                onwillreconnect: onChatroomWillReconnect,
                ondisconnect: onChatroomDisconnect,
                // 消息
                onmsgs: onChatroomMsgs
            });
        }

    }
}

function onChatroomConnect(chatroom) {
    console.log('进入聊天室', chatroom);

    //获取历史消息
    chatroomObj.getHistoryMsgs({
        //timetag: 1451393192478,  // 不填表示当前时间戳
        limit: 50,
        done: getHistoryMsgsDone

    });
}

//console.log('正在发送聊天室text消息, id=' + msg.idClient);
function sendChatroomMsgDone(error, msg) {
    console.log('发送聊天室' + msg.type + '消息' + (!error?'成功':'失败') + ', id=' + msg.idClient, error, msg);
    if(!error){
        getMessage(msg);
        write_chat_record(msg);
    }
}

//收到聊天室消息
function onChatroomMsgs(msgs) {
    var msg = msgs[0];
    getMessage(msg);
    console.log('收到聊天室消息', msgs);
}

function getHistoryMsgsDone(error, obj) {
    console.log('获取聊天室历史' + (!error?'成功':'失败'), error, obj.msgs);
    msgReturnNum = obj.msgs.length;
    if (msgReturnNum == msgGetNum) {
        $("#view_history_news").show();
    } else {
        $("#view_history_news").hide();
    }
    if(!error && obj.msgs.length > 0){
        var message_count = 0;
        for(var i=0;i<obj.msgs.length;i++) {
            var msg = obj.msgs[i];

            $(".no-comment").css('display', 'none');
            timeStamp = msg.time;

            if (msg.type == 'text' || msg.type == 'image' || msg.type == 'audio') {
                message_count++;
                $("#message_box").prepend(message_html(msg));
            }
        }


        if(msgReturnNum == msgGetNum && message_count < 10){
            chatroomObj.getHistoryMsgs({
                timetag: timeStamp,  //不填表示当前时间戳
                limit: msgGetNum,
                done: getHistoryMsgsDone
            });
        }

        if (isClickHistory == false) {
            footerfunction();
        }
    }
}

/**
 * 返回消息html
 * @param type 类型 文本，图片，语音
 * @param avatar 头像
 * @param name 昵称
 * @param content 消息内容
 * @param timeStamp 消息时间戳
 * @returns {*}
 */
function message_html(msg) {

    type = msg.type;
    avatar = msg.fromAvatar;
    name = msg.fromNick;

    if (type == 'text') {
        content = '<span class="font">' + buildEmoji(msg.text) + '</span>';
    } else if (type == 'image') {
        content = '<span class="font"><img src="'+ msg.file.url + '" style="height:100px;" onclick="imgbig(this)"></span>';
    } else if (type == 'audio') {
        var audio_id = msg.idClient;
        var audio_time = Math.ceil(msg.file.dur/1000);
        var from = msg.from;

        if (from == account) {
            content =audio_xiaohongdian(audio_id) + '<span class="font">' +  audio_time + 's' + '<img onclick="playaudio(\''+audio_id+'\',\''+from+'\')" style="padding-top:3px; width:50%;" src="business/style/chat_audio_static_r.png" alt=""> <audio  id="'+audio_id+'" src="'+msg.file.url+'" audio_time="'+ audio_time +'" ></audio> '+ '</span>';
        } else {
            content ='<span class="font">' +'<img onclick="playaudio(\''+audio_id+'\',\''+from+'\')" style="padding-top:3px; width:50%;" src="business/style/chat_audio_static.png" alt=""> <audio  id="'+audio_id+'" src="'+msg.file.url+'" audio_time="'+ audio_time +'" ></audio> ' + audio_time + 's'+ '</span>'+ audio_xiaohongdian(audio_id);
        }
    }


    str = '';
    if (type == 'text' || type == 'image' || type == 'audio') {

        //自己发的消息
        if (msg.from == account) {
            str = "<div class='chat-time'>"+getTime(msg.time)+"</div>" +
            '<div class="chat-item-m">' +
            '<div class="style2">' +
            '<div class="chat-item-img">' +
            '<img src="'+avatar+'" >' +
            '</div>' +
            '</div>' +
            '<div class="chat-item-contr">' +
            //'<div class="name">'+name+'</div>' +
            content +
            '</div>' +
            '<div class="clear"></div>' +
            '</div>';
        } else {
            str = "<div class='chat-time'>"+getTime(msg.time)+"</div>" +
            '<div class="chat-item-o">' +
            '<div class="style1">' +
            '<div class="chat-item-img">' +
            '<img src="'+avatar+'" >' +
            '</div>' +
            '</div>' +
            '<div class="chat-item-contl">' +
            '<div class="name">'+name+'</div>' +
            content +
            '</div>' +
            '<div class="clear"></div>' +
            '</div>';
        }
    }
    return str;
}

function audio_xiaohongdian(audio_id) {
    str = '';
    if (common.getCookie(audio_id) == '') {
        str = ' <span red_id="'+audio_id+'" style="display:inline-block;padding:0 4px;padding-top:22px;"><img src="business/style/xiaohongdian.gif" alt=""></span> ';
    }
    return str;
}


//接收消息显示
function getMessage(msg){
    console.log("接收消息：" + JSON.stringify(msg));
    $('#message_box').append(message_html(msg));
    $("#message").val("");
    footerfunction();
}

function getTime(date){
    date = new Date(parseInt(date));
    // var year = date.getFullYear();
    var month = date.getMonth()+1;
    var day = date.getDate();
    var hour = date.getHours();
    var minute = date.getMinutes();
    //var second=date.getSeconds();
    if(month < 10){
        month = '0'+month;
    }
    if(day < 10){
        day = '0'+day;
    }
    if(hour < 10){
        hour = '0'+hour;
    }
    if(minute < 10){
        minute = '0'+minute;
    }
    //if(second < 10){
    //    second = '0'+second;
    //}
    return month+'-'+day+' '+hour+':'+minute;

}

function onChatroomWillReconnect(obj) {
    // 此时说明 `SDK` 已经断开连接, 请开发者在界面上提示用户连接已断开, 而且正在重新建立连接
    console.log('即将重连', obj);
}

function onChatroomDisconnect(error) {
    clearInterval(online_time_interval);
    // 此时说明 `SDK` 处于断开状态, 开发者此时应该根据错误码提示相应的错误信息, 并且跳转到登录页面
    console.log('连接断开', error);
    if (error) {
        switch (error.code) {
            // 账号或者密码错误, 请跳转到登录页面并提示错误
            case 302:
                break;
            // 被踢, 请提示错误后跳转到登录页面
            case 'kicked':
                break;
            default:
                break;
        }
    }
}

function onChatroomError(error, obj) {
    console.log('发生错误', error, obj);
}

function funtxtsend(){
    $(".txtsendbg").show(function(){
        $("#message").focus();
    });
    $(".txtsendcontent").show();
    if(isAndroid){
        $(".class_talk_con_header").hide();
    }
}

function closetxtsend(){
    $(".txtsendbg").hide();
    $(".txtsendcontent").hide();
    footerfunction();
    $(".class_talk_con_header").show();
}

function sendover(){
    $("#qq").hide();
    $(".txtsendbg").hide();
    $(".txtsendcontent").hide();
    footerfunction();
    $(".class_talk_con_header").show();
}

function footerfunction(){
    e1=document.getElementById("big-chat");
    h=e1.scrollHeight;
    document.documentElement.scrollTop=h;
    window.pageYOffset =h;
    document.body.scrollTop=h;
}

function imgbig(obj){
    if(isAndroid){
        $(".class_talk_con_header video").hide();
    }
    $("#imgbbig").show();
    $(".imgbbigdiv").show();
    var img=$(obj).attr('src');
    $(".pinch-zoom").find("img").attr("src",img);
}

function imgbigclose(){
    $("#imgbbig").hide();
    $(".imgbbigdiv").hide();
}

function startluyin(){
    wx.startRecord({
        cancel: function () {
            alert('用户拒绝授权录音');
        }
    });
}

function stopluyin(){
    wx.stopRecord({
        success: function (res) {
            send_record(res)
        },
        fail: function (res) {
            alert(JSON.stringify(res));
        }
    });
}

function auto_stop(){
    wx.onVoiceRecordEnd({
        // 录音时间超过一分钟没有停止的时候会执行 complete 回调
        complete: function (res) {
            send_record(res);
            chatyl();
        }
    });
}

function close_audio_icon(voiceid, from) {
    if (from == account) {
        $("#"+voiceid).prev().attr("src", "business/style/chat_audio_static_r.png");
    } else {
        $("#"+voiceid).prev().attr("src", "business/style/chat_audio_static.png");
    }

}

function play_audio_icon(voiceid, from) {
    if (from == account) {
        $("#"+voiceid).prev().attr('src', 'business/style/chat_audio_play_r.gif');
    } else {
        $("#"+voiceid).prev().attr('src', 'business/style/chat_audio_play.gif');
    }
}


//播放声音
function playaudio(voiceid, from) {
    if($("#"+voiceid)[0].paused) {
        $("#"+voiceid)[0].play();
        play_audio_icon(voiceid, from);

        common.setCookie(voiceid, 1, 180);
        $("span[red_id='"+ voiceid +"']").remove();

        //播放完毕切换提示图标
        var aud = document.getElementById(voiceid);
        aud.onended = function() {
            close_audio_icon(voiceid, from);
        };

    } else {
        $("#"+voiceid)[0].pause();
        $("#"+voiceid)[0].currentTime = 0;
        close_audio_icon(voiceid, from);
    }

    // $("#"+serceridone).attr("ok1",0);
    if(voiceid != voiceidone && voiceidone.length > 0) {
        if(!$("#"+voiceidone)[0].paused){
            $("#"+voiceidone)[0].pause();
            $("#"+voiceidone)[0].currentTime=0;
            close_audio_icon(voiceidone, from);
        }
    }
    voiceidone = voiceid
}

//发送录音
function send_record(res){
    localId = res.localId;
    wx.uploadVoice({
        localId: localId,
        success: function (res) {
            serverId = res.serverId;
            re = common.get('group', 'downLoadWxFile', {'serverId':serverId});
            console.log('下载音频：'+JSON.stringify(re));
            if (re.result == 0) {
                file = re.datas;
                var msg = chatroomObj.sendFile({ 
                    file: file,
                    type : 'audio',
                    done: sendChatroomMsgDone
                });
                console.log('正在发送聊天室audio消息, id=' + msg.idClient);
            }
        }
    });
}

function chatyl(){
    $(".closeabs").hide();
    $("#class_talk_con_footer_frame").removeClass("audio_xx");
    $(".m_show").show();
    $(".m_hide").hide();
    if(!$(".class_talk_con_footer_icon_audio_on").attr("luyin")){
        stopluyin1();
    };
    $(".time-bg").hide();
    $(".class_talk_con_footer_icon_audio_on").show();
    $(".class_talk_con_footer_icon_audio_off").hide();
    clearTimeout(dingshi)
}

function show123(变量) {
    $(".time").text(变量+"s");
    var now=变量-1;
    if(parseInt(变量) >0){
        dingshi=setTimeout(function () {
            show123(now);
        }, 1000);
    }
}

//保存聊天记录
function write_chat_record(msg) {
    if (msg.type == 'text') {
        type = '文本';
        message = msg.text;
    } else if (msg.type == 'image' ) {
        type = '图片';
        message = msg.file.url;
    } else if (msg.type == 'audio') {
        type = '语音';
        message = msg.file.url;
    } else {
        return false;
    }

    param = {
        'groupId' : groupId,
        'type' : type,
        'message' : message
    };
    re = common.post('course', 'write_chat_record', param);
    console.log('保存聊天记录：' + JSON.stringify(re));
}

//记录在线时长
function online_time() {
    common.post('group', 'out_group_lx', {'groupId':groupId});
}
